'use client';

import Link from 'next/link'
import { usePathname, useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';

// 哲思-数组
const thoughts = [
    {
        text: "我生而为人，有双腿可以自由地奔跑，有双手可以自由地创造。如小鸟生而有翼，可以展翅高飞，云朵之上的世界，比地面更精彩，回到地面，不见得会有真正的安全。",
        author: "万维钢",
    },
    {
        text: "人生就像一场旅行，不在乎目的地，在乎的是沿途的风景以及看风景的心情。",
        author: "林清玄",
    },
    {
        text: "生活不是等待暴风雨过去，而是要学会在雨中跳舞。",
        author: "林清玄",
    }
]

// 基于时间戳的伪随机选择，确保服务端和客户端一致
function getThoughtByTime() {
    const now = new Date();
    const hour = now.getHours();
    const dayOfYear = Math.floor((now.getTime() - new Date(now.getFullYear(), 0, 0).getTime()) / 86400000);
    const index = (hour + dayOfYear) % thoughts.length;
    return thoughts[index];
}

export default function ClientLayout({
    children,
}: Readonly<{
    children: React.ReactNode
}>) {
    const pathname = usePathname();
    const searchParams = useSearchParams();
    const [categories, setCategories] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    // 获取分类数据
    useEffect(() => {
        const fetchCategories = async () => {
            try {
                const response = await fetch('http://127.0.0.1:9090/categories');
                const result = await response.json();
                const data = result.data.list;
                console.log('分类数据', data);

                // 简单处理数据，不严格验证类型
                let categoriesData: any[] = [];

                // 如果是数组直接用
                if (Array.isArray(data)) {
                    categoriesData = data;
                } else if (data && typeof data === 'object') {
                    // 尝试从常见字段中获取数组
                    if (Array.isArray(data.categories)) {
                        categoriesData = data.categories;
                    } else {
                        // 找到第一个数组字段
                        const arrayField = Object.keys(data).find(key => Array.isArray(data[key]));
                        if (arrayField) {
                            categoriesData = data[arrayField];
                        } else {
                            throw new Error('没有找到分类数据');
                        }
                    }
                } else {
                    throw new Error('数据格式错误');
                }

                // 简单过滤，只要有id和name就行
                const validCategories = categoriesData.filter((cat: any) =>
                    cat && cat.id && cat.name
                );

                if (validCategories.length === 0) {
                    throw new Error('没有找到有效的分类数据');
                }

                setCategories(validCategories);

            } catch (err) {
                console.error('获取分类失败:', err);
                const errorMessage = err instanceof Error ? err.message : '获取分类失败';
                setError(errorMessage);
                throw new Error(errorMessage);
            } finally {
                setLoading(false);
            }
        };

        fetchCategories();
    }, []);

    useEffect(() => {
        console.log('路由变化', pathname, searchParams.toString());
    }, [pathname, searchParams]);

    // 获取当前时间对应的哲思
    const selectedThought = getThoughtByTime();

    // 错误状态直接抛出错误，让错误边界处理
    if (error) {
        throw new Error(error);
    }

    return (
        <div className="container">
            <div className="sidebar">
                <div className="top">
                    <img src="/assets/images/logo.png" alt="" />
                    <div className="title">
                        <div>Birds have no wings</div>
                    </div>
                </div>
                <hr />
                <div className="menu">
                    {loading ? (
                        // 加载状态显示加载中
                        <span style={{ color: '#999', fontSize: '14px' }}>加载分类中...</span>
                    ) : (
                        <>
                            <Link href="/">首页</Link>
                            {
                                categories.map((category) => (
                                    <Link
                                        key={category.id}
                                        href={`/?category_id=${encodeURIComponent(category.id)}`}
                                    >
                                        {category.name}
                                    </Link>
                                ))
                            }
                            <Link href="/about">关于</Link>
                        </>
                    )}
                </div>
                <hr />
                <div className="intr">
                    <div className="intrTitle">哲思</div>
                    {/* 哲思-基于时间选择，避免闪烁 */}
                    <div className="intrText">
                        {selectedThought.text}
                        <span></span>
                    </div>
                    <div className="sign">—— {selectedThought.author}</div>
                </div>
            </div>
            <div className="content">{children}</div>
        </div>
    )
}